package com.gitee.wsl.doc.prosemirror.state.ext

import com.gitee.wsl.doc.prosemirror.model.content.ResolvedPos
import com.gitee.wsl.doc.prosemirror.model.node.ext.canJoin
import com.gitee.wsl.doc.prosemirror.state.CommandDispatch
import com.gitee.wsl.doc.prosemirror.state.EditorState
import com.gitee.wsl.doc.prosemirror.transform.ext.delete
import com.gitee.wsl.doc.prosemirror.transform.ext.join

fun EditorState.joinMaybeClear(
    pos: ResolvedPos,
    dispatch: CommandDispatch?
): Boolean {
    val state = this
    val before = pos.nodeBefore
    val after = pos.nodeAfter
    val index = pos.index()

    // 检查前后节点是否存在且内容类型兼容
    if (before == null || after == null || !before.type.compatibleContent(after.type)) {
        return false
    }

    // 如果前节点内容为空且父节点允许替换，则执行删除操作
    if (before.content.size == 0 && pos.parent.canReplace(index - 1, index)) {
        if (dispatch != null) {
            val tr = state.tr.delete(pos.pos - before.nodeSize, pos.pos).scrollIntoView()
            dispatch(tr)
        }
        return true
    }

    // 检查是否可以进行合并操作
    if (!pos.parent.canReplace(index, index + 1) ||
        !(after.isTextblock || state.doc.canJoin( pos.pos))) {
        return false
    }

    // 执行合并操作
    if (dispatch != null) {
        val tr = state.tr.join(pos.pos).scrollIntoView()
        dispatch(tr)
    }
    return true
}